;(function () {
  var Edit = window.wangEditor
  var editor = new Edit('#editor')
  editor.customConfig.zIndex = 100
  editor.customConfig.uploadImgServer = uploadUrl
  editor.customConfig.uploadFileName = 'file'
  editor.customConfig.customAlert = function (info) {}
  editor.customConfig.uploadImgHooks = {
      // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
      // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
      customInsert: function (insertImg, result, editor) {
          // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
          // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
          // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
          var url = result.url
          insertImg(url)
      }
  }

  // editor.txt.html()  读取内容
  // editor.txt.html('<p>用 JS 设置的内容</p>')   设置内容

  new Vue({
    el: '#cEnd-create',
    data: {
      flag: false,
      isImage: ['.jpg', '.jpeg', '.gif', '.png', '.bmp'],
      files: [],
      stateList: [],
      modulesList: [],
      moduleId: '',
      articleTitle: '',
      abstract: '',
      listImg: '',
      memo: '',
      status: '',
			// 2019-1-29 begin
			participateLt: [{name: '是', code: 'Y'}, {name: '否', code: 'N'}],
			participateAt: 'Y',
			dateTime: {begin: '', end: '', isDefalut: false},
			buttonName: '',
			moduleLt: [],
			fieldLt: [],
			isValidateLt: [{name: '是', code: true}, {name: '否', code: false}],
			moudleIndex: null,
      // 2019-1-29 end,
      isShowTemplate:false, //是否显示提交模板
      progress:'',
    },
    methods: {
			// 2019-1-29 begin
			participateSel (item) {
				this.participateAt = item.code
			},
			longTrem () {
				this.dateTime.isDefalut = !this.dateTime.isDefalut;
				if (this.dateTime.isDefalut) {
					this.dateTime = {begin: '', end: '', isDefalut: true}
				}
			},
			fieldConfig () {
				hlhttp.get({
					url: 'configure/dict',
					data: {module_code: 'MNHU', config_name: 'MNHU_ACTIVITY_PARTICIPATE_TYPE'},
					success: (data) => {
						this.fieldLt = data;
					}
				})
			},
			addMoudle () {
				let flag = false;
				this.moduleLt.map(item => {
					if (!item.name) {
						flag = true;
					}
					if (!item.type) {
						flag = true;
					}
					if (!item.range) {
						flag = true;
					}
					if (item.flag0) {
						flag = true;
					}
					if (item.flag1) {
						flag = true;
					}
				})
				if (flag) {
					hl.toast('请先保存当前信息')
					return
				}
				this.moduleLt.push({name: '', oldName: '', type: '', type_name: '', range: '', oldRange: '', is_required: true, placeholder: '', flag0: true, flag1: true})
			},
			queryName (i, type) {
				if (type) {
					if (type == 'confirm') {
						if (!this.moduleLt[i].name) {
							hl.toast('自定义名称不能为空')
							return
						}
					}
					if (type == 'cancel') {
						if (!this.moduleLt[i].oldName) {
							this.moduleLt.splice(i, 1)
							return
						}
						this.moduleLt[i].name = JSON.parse(JSON.stringify(this.moduleLt[i].oldName))
					}
				}

				this.moduleLt[i].oldName = JSON.parse(JSON.stringify(this.moduleLt[i].name))
				this.moduleLt[i].flag0 = !this.moduleLt[i].flag0
			},
			typeSel (item, i) {
				if (this.moduleLt[i].type != item.dictCode) {
					this.moduleLt[i].flag1 = true;
					this.moduleLt[i].range = '';
				}
				this.moduleLt[i].type = item.dictCode;
				this.moduleLt[i].type_name = item.dictName;
				if (this.moduleLt[i].type) {
					if (this.moduleLt[i].type == 'text' || this.moduleLt[i].type == 'textarea') {
						this.moduleLt[i].placeholder = '请填写数字'
					}
					if (this.moduleLt[i].type == 'radio' || this.moduleLt[i].type == 'checkbox') {
						this.moduleLt[i].placeholder = '请用英文逗号分隔'
					}
					if (this.moduleLt[i].type == 'datepicker' || this.moduleLt[i].type == 'timepicker') {
						this.moduleLt[i].range = '#'
						this.moduleLt[i].placeholder = '#'
						this.moduleLt[i].flag1 = false
						this.moduleLt[i].flag0 = false
					}
				}
			},
			queryRange (i, type) {
				if (!this.moduleLt[i].type) {
					hl.toast('请选择类型')
					return
				}
				if (type) {
					if (type == 'confirm') {
						if (!this.moduleLt[i].range) {
							hl.toast('取值范围不能为空')
							return
						}
					}
					if (type == 'cancel') {
						if (!this.moduleLt[i].oldRange) {
							this.moduleLt.splice(i, 1)
							return
						}
						this.moduleLt[i].range = JSON.parse(JSON.stringify(this.moduleLt[i].oldRange))
					}
				}

				this.moduleLt[i].oldRange = JSON.parse(JSON.stringify(this.moduleLt[i].range))
				this.moduleLt[i].flag1 = !this.moduleLt[i].flag1
			},
			isValidateSel (item, i) {
				this.moduleLt[i].is_required = item.code;
			},
      showTemplate() {
        this.isShowTemplate = !this.isShowTemplate
      },
			delOneModule () {
				if (!this.moudleIndex && this.moudleIndex != 0) return;
				this.moduleLt.splice(this.moudleIndex, 1)
				this.moudleIndex = null;
			},
			// 2019-1-29 end

      //文件上传click()触发
      fileUp () {
        if(this.progress){
          hl.toast('文件尚未上传完成')
          return
        }
        $('.fileButton').trigger('click')
      },
      fileToClick () {
        var that = this
        fileUpload('.fileButton', uploadUrl, (data) => {
          let type = data.json.name.substr(data.json.name.lastIndexOf('.'))
          if (this.isImage.indexOf(type) > -1) {
            this.files.push({name: data.json.name, url: data.json.url, type: 'pic'})
          }
          if (this.isImage.indexOf(type) == -1) {
            this.files.push({name: data.json.name, url: data.json.url, type: 'file'})
          }
        },function(val){
          that.progress = parseInt((val.loaded/val.total)*100) + '%'
        })
      },
      //图片上传click()触发
      picUp () {
        $('.picButton').trigger('click')
      },
      picToClick () {
        imgupload('.picButton', uploadUrl, (data) => {
          this.listImg = data.json.url
        })
      },
      //获取状态
      getoffOn () {
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'CMMN', config_name: 'CM_ENABLE_STATUS'},
          success: (data) => {
            this.stateList = data
          }
        })
      },
      //模块列表获取
      getmodules () {
        hlhttp.get({
          url: 'portal/modules',
          success: (data) => {
            this.modulesList = data;
          }
        })
      },
      //获取模块id
      eventModule (id, type) {
        this.moduleId = id;
        if (type == 'ATCLS') {
          this.flag = false
        }
        if (type == 'ATCLM') {
          this.flag = true
        }
      },
      //获取状态
      eventStatus (code) {
        this.status = code
      },
      //删除指定附件
      delFile (index) {
        this.files.splice(index, 1)
      },
      //验证
      validateInfo () {
        if (!this.moduleId) {
          hl.toast('请选择发布模块')
          return false
        }
        if (!this.articleTitle) {
          hl.toast('请填写文章标题')
          return false
        }
        if (this.flag) {
          if (!this.listImg) {
            hl.toast('请上传列表图')
            return false
          }
        }
        if (!editor.txt.html().length) {
          hl.toast('请填写内容详情')
          return false
        }
        if (!this.status) {
          hl.toast('请选择状态')
          return false
        }
				let flag = true, str = '';
				for (let i = 0; i < this.moduleLt.length; i++) {
					let item = this.moduleLt[i];
					if (!item.name) {
						str = '请填写自定义名称'
						flag = false;
						break;
					}
					if (!item.type) {
						str = '请选择类型'
						flag = false;
						break;
					}
					if (!item.range) {
						str = '请填写取值范围'
						flag = false;
						break;
					}
				}
				if (!flag) {
					hl.toast(str)
				}
        return flag
      },
      //保存
      saveSubmit () {
        if (!this.validateInfo()) {return};
        let url = [], name = [];
        this.files.map(item => {
          url.push(item.url)
          name.push(item.name)
        })
				let longTerm = '#';
				if (this.participateAt == 'Y') {
					longTerm = this.dateTime.isDefalut ? 'Y' : 'N'
				}
        hlhttp.post({
          url: 'portal/publishing',
          data: {
            module_id: this.moduleId,
            title: this.articleTitle,
            introduction: this.abstract || '#',
            thumb_url: this.listImg || '#',
            content: editor.txt.html(),
            attachments_url: url.toString() || '#',
            attachments_name: name.toString() || '#',
            memo: this.memo,
            status: this.status,
						//new add
						is_partake: this.participateAt,
						begin_time: this.dateTime.begin || '#',
						end_time: this.dateTime.end || '#',
						is_long_term_flag: longTerm,
						button_name: this.buttonName || '#',
						option_rows: this.moduleLt.length ? JSON.stringify(this.moduleLt) : '#'
          },
          success: (data) => {
            hlUrlUtil.goTo('previewInfo98k',{ddtab: true, portalArticleId: data.portalArticleId, clear: true},false)
          }
        })
      },
      //预览
      previewInfo () {
        if (!this.validateInfo()) {return};
        let data = {
          title: this.articleTitle,
          introduction: this.abstract || '#',
          thumb_url: this.listImg || '#',
          content: editor.txt.html(),
          files: this.files,
          memo: this.memo
        }
        window.sessionStorage.setItem('previewInfo', JSON.stringify(data))
        hlUrlUtil.goTo('previewInfo98k',{ddtab: true},true)
      }
    },
    created () {
      hlSelectUi()
    },
    mounted () {
      editor.create()
      this.fileToClick()
      this.picToClick()
      this.getoffOn()
      this.getmodules()
			this.fieldConfig()
    }
  })
} ())
